<script>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { api } from '../api'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

export default {
  name: 'AddCategory',
  setup() {
    const userStore = useUserStore()
    const router = useRouter()

    const categoryForm = reactive({
      name: ''
    })

    const categoryFormRef = ref(null)

    const rules = {
      name: [
        { required: true, message: '请输入类别名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ]
    }

    // 提交表单
    const submitForm = async () => {
      const form = categoryFormRef.value
      if (!form) return

      try {
        await form.validate()
        console.log('表单验证通过')

        const submitData = {
          name: categoryForm.name,
          userId: userStore.userInfo?.id || userStore.userInfo?.stuNum || userStore.userInfo?.username || 'default_user'
        }

        const response = await request.post('/additem?typeIndex=5', submitData)
        console.log('API响应:', response)

        if (response?.errno === 0) {
          ElMessage.success('课程类别添加成功')
          resetForm()

          // 关键修复：添加成功后，重新获取类别列表（通知其他页面数据已更新）
          setTimeout(() => {
            router.push('/home').then(() => {
              router.go(0) // 刷新首页，强制重新获取数据
            })
          }, 500)
        } else {
          ElMessage.error(response?.message || '添加失败，请稍后重试')
        }
      } catch (error) {
        console.error('添加类别失败:', error)
        if (error.name !== 'ValidateError') {
          ElMessage.error('网络错误，请稍后重试')
        }
      }
    }

    // 重置表单
    const resetForm = () => {
      const form = categoryFormRef.value
      if (form) {
        form.resetFields()
      }
    }

    // 组件挂载时初始化
    onMounted(() => {
      // 可以在这里添加初始数据加载逻辑
    })

    return {
      categoryForm,
      rules,
      categoryFormRef,
      submitForm,
      resetForm
    }
  }
}
</script>